package com.thx.common.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Random;

/**
 * 生成图片验证码.
 *
 * @author balance
 */
public class CaptchaUtil {

  public static final String CAPTCHA_NAME = "captcha_name";

  // 干扰线数
  private static final int lineNumber = 100;

  /**
   * 创建一个验证码图片.
   *
   * @param width 图片宽度
   * @param height 图片高度
   * @param randomText 随机的文本
   * @return 验证码图片
   */
  public static BufferedImage creatCaptcha(int width, int height, String randomText) {
    long seed = new Date().getTime();
    Random random = new Random(seed);

    // 创建图形
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics graphics = image.getGraphics();

    // 画矩形框
    graphics.setColor(getRandColor(200, 250));
    graphics.fillRect(0, 0, width, height);

    // 画不同颜色的线
    graphics.setFont(new Font("宋体", Font.PLAIN, 18));
    for (int i = 0; i < lineNumber; i++) {
      graphics.setColor(getRandColor(160, 200));
      int xp = random.nextInt(width);
      int yp = random.nextInt(height);
      int xl = random.nextInt(12);
      int yl = random.nextInt(12);
      graphics.drawLine(xp, yp, xp + xl, yp + yl);
    }

    // 画随机文本
    for (int i = 0; i < randomText.length(); i++) {
      graphics.setColor(
          new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
      graphics.drawString(randomText.substring(i, i + 1), 13 * i + 6, 16);
    }

    graphics.dispose();
    return image;
  }

  /**
   * 随机生成颜色.
   *
   * @param fc 前景值范围
   * @param bc 背景值范围
   * @return 随机颜色
   */
  private static Color getRandColor(int fc, int bc) {
    long seed = new Date().getTime();
    Random random = new Random(seed);
    if (fc > 255) {
      fc = 255;
    }
    if (bc > 255) {
      bc = 255;
    }
    int red = fc + random.nextInt(bc - fc);
    int green = fc + random.nextInt(bc - fc);
    int blue = fc + random.nextInt(bc - fc);
    return new Color(red, green, blue);
  }
}
